package com.sushi.config;

import com.sushi.exception.BusinessException;
import com.sushi.response.ResponseBO;
import com.sushi.utils.ResponseUtil;
import org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.FileNotFoundException;
import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @author wywei
 */
@RestControllerAdvice(annotations = {RestController.class})
public class GlobalExceptionCatcher {

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public ResponseBO<String> exceptionHandler(SQLIntegrityConstraintViolationException ex) {
        if (ex.getMessage().contains("Duplication entry")) {
            return ResponseUtil.error(ex.getMessage().split(" ")[2] + "已存在!");
        }
        return ResponseUtil.error("未知错误");
    }
    @ExceptionHandler(FileNotFoundException.class)
    public ResponseBO<String> fileNotFound(FileNotFoundException ex) {
        return ResponseUtil.error("文件加载失败");
    }

    @ExceptionHandler(BusinessException.class)
    public ResponseBO<String> businessException(BusinessException ex) {
        return ResponseUtil.error(ex.getMessage());
    }
    @ExceptionHandler(FileSizeLimitExceededException.class)
    public ResponseBO<String> imageException(FileSizeLimitExceededException ex) {
        return ResponseUtil.error("文件过大");
    }


}
